package com.letianpai.activity.family;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.OfflineMessageManager;
import org.jivesoftware.smackx.packet.DelayInformation;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.letianpai.R;
import com.letianpai.activity.LoginActivity;
import com.letianpai.activity.NotifyActivity;
import com.letianpai.activity.chat.ChatActivity;
import com.letianpai.activity.chat.SelectChatsActivity;
import com.letianpai.activity.home.SetActivity;
import com.letianpai.adapter.family.FamilyListAdapter;
import com.letianpai.bean.BackUserinformation;
import com.letianpai.bean.FriendInfo;
import com.letianpai.bean.GroupInfo;
import com.letianpai.bean.InviteUser;
import com.letianpai.bean.Msg;
import com.letianpai.db.ChatInformation;
import com.letianpai.db.Constant;
import com.letianpai.db.DBUtiles;
import com.letianpai.db.RequestDBUtils;
import com.letianpai.db.RequestInformation;
import com.letianpai.db.bean.UserInfo;
import com.letianpai.db.cache.UserCache;
import com.letianpai.dialog.CustomDialog;
import com.letianpai.http.RequestBean.GetInformation;
import com.letianpai.http.RequestBean.GetInformationBean;
import com.letianpai.http.RequestBean.UserinformationData;
import com.letianpai.service.XmppService;
import com.letianpai.utils.ChatUtils;
import com.letianpai.utils.DialUtils;
import com.letianpai.utils.JsonUtil;
import com.letianpai.utils.TimeRender;
import com.letianpai.utils.Utils;
import com.letianpai.utils.XmppTool;

public class FamilyListActivity extends Activity {
	private Roster roster;
	public static ArrayList<FriendInfo> arrayList;// 好友列表
	String USERID;
	String chatUserId;
	private List<GroupInfo> groupList;
	public static int FAMILY_CODE = 203;
	GroupInfo groupInfo;
	FriendInfo friendInfo;
	public static UserinformationData ui;
	RequestQueue requestQueue;
	ImageView add_family, seek_family, notify_family, set;
	Intent intent;
	public static FamilyListAdapter fd;
	private String pGROUPNAME = "我的好友";// 当前组
	private String pUSERID;// 当前用户
	private String fromUserJid = null;// 发送邀请的用户的userJid
	private String toUserJid = null;// 收到邀请的用户的userJid
	SharedPreferences sp;
	Editor editor;
	XMPPConnection connection = null;
	public static Bitmap mb;
	public static String nickname;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.family_contacts);

		sp = getSharedPreferences("myPref", MODE_WORLD_READABLE);
		final String username = sp.getString("username", "1");
		final String password = sp.getString("password", "1");
		initView();// 初始化
		connection = XmppTool.con;
		if (!username.equals("1") && connection == null) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						XmppTool.getConnection().login(username, password);
						// 状态
						Presence presence = new Presence(
								Presence.Type.unavailable);
						XmppTool.getConnection().sendPacket(presence);
						// 登录openfire

						handle.sendEmptyMessage(19);
						editor = sp.edit();
						editor.putString("islogin", "0");
						editor.commit();
						connection = XmppTool.con;
					} catch (XMPPException e) {
					} catch (IllegalStateException e) {
					}

				}

			}).start();
		} else {

			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(1000);
						handle.sendEmptyMessage(19);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();

		}

	}

	/*
	 * 判断是否邀请注册
	 */
	public void isInvite() {
		if (null != LoginActivity.ui) {
			InviteUser iu = LoginActivity.ui.getInvite_user();
			if (!(iu.getInvite_from_username() == null)) {
				// 发送加好友的消息
				String groupName = "我的好友";
				XmppService.addUsers(roster, iu.getInvite_from_username()
						+ "@ay14050414574271995az",
						iu.getInvite_from_username(), groupName);
			}
		}

	}

	/*
	 * 监听消息 只要成功登陆就会收到消息
	 */
	public void monitorMessage() {
		// 消息监听

		cm = XmppTool.getConnection().getChatManager();
		cm.addChatListener(new chatListener());
		// 状态
		Presence presence = new Presence(Presence.Type.available);
		XmppTool.getConnection().sendPacket(presence);
	}

	// 实现消息监听
	class chatListener implements ChatManagerListener {

		@Override
		public void chatCreated(Chat chat, boolean able) {
			// 监听收到的消息
			chat.addMessageListener(new MessageListener() {

				@Override
				public void processMessage(Chat arg0,
						org.jivesoftware.smack.packet.Message message) {
					String messageFrom = message.getFrom();
					DelayInformation inf = (DelayInformation) message
							.getExtension("x", "jabber:x:delay");
					Date sentDate;
					if (inf != null) {
						sentDate = inf.getStamp();
					} else {
						sentDate = new Date();
					}
					Log.d("zzzz", sentDate.toLocaleString());
					String name = sp.getString("remind", "2");
					Log.d("zzzz", name);
					if (name.equals("0")) {
						Log.d("zzzz", "播放音乐");
						DialUtils.playMusic(FamilyListActivity.this,
								R.raw.office);
					}
					Log.d("zzzz", message.getBody() + "这里是familyList监听到好友消息");
					for (FriendInfo info : arrayList) {

						if ((info.getUsername() + "@ay14050414574271995az/Smack")

						.equals(messageFrom)) {
							info.setMessageCount(info.getMessageCount() + 1);
							ChatInformation chatif = new ChatInformation();
							chatif.setChatInformation(message.getBody());
							chatif.setuId(info.getUsername()
									+ "@ay14050414574271995az");
							Log.d("zzzz", "保存");
							DBUtiles.saveChatInformation(chatif,
									FamilyListActivity.this, USERID);
							Gson gson = new Gson();
							Msg msg = new Msg();
							msg = gson.fromJson(message.getBody(),
									new TypeToken<Msg>() {
									}.getType());

							Intent intent = new Intent();
							intent.setAction("cn.abel.action.broadcast");
							intent.putExtra("from", messageFrom);
							intent.putExtra("msg", msg);
							FamilyListActivity.this.sendBroadcast(intent);
						}
					}
					fd.setArrayList(arrayList);
					fd.notifyDataSetChanged();
				}

			});
		}
	}

	/*
	 * 加载好友列表
	 */
	public void familyList() {
		groupList = new ArrayList<GroupInfo>();
		Collection<RosterEntry> groups = roster.getEntries();
		arrayList = new ArrayList<FriendInfo>();
		arrayList.clear();
		new Thread(new Runnable() {

			@Override
			public void run() {
				post();
			}
		}).start();
		try {

			mb = ChatUtils.getUserImage(sp.getString("username", ""));
			nickname = ChatUtils.getname(sp.getString("username", ""));
			Log.d("zzzz", nickname);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 好友列表

		for (RosterEntry entry : groups) {
			chatUserId = entry.getUser();
			if ("both".equals(entry.getType().name())) {// 只添加双边好友
				friendInfo = new FriendInfo();
				friendInfo.setUsername(Utils.getJidToUsername(entry.getUser()));
				String nick = ChatUtils.getname(Utils.getJidToUsername(entry
						.getUser()));
				if (nick == null) {
					friendInfo.setNickname(entry.getName());
				} else {
					friendInfo.setNickname(nick);
				}
				try {
					Bitmap mp = ChatUtils.getUserImage(Utils
							.getJidToUsername(entry.getUser()));

					friendInfo.setPic(mp);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				friendInfo.setMessageCount(0);
				arrayList.add(friendInfo);
				Log.d("zzzz", arrayList.size() + "好友的个数");
				friendInfo = null;
			}
		}

		USERID = sp.getString("username", "1");
		fd = new FamilyListAdapter(this, arrayList, new FamilyClick());
		lv = (ListView) findViewById(R.id.listView);
		lv.setAdapter(fd);
		lv.setOnItemLongClickListener(new FamilyLongClick());
	}

	// 条目长按事件
	class FamilyLongClick implements OnItemLongClickListener {

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			final String deName = arrayList.get(position).getJid();
			dialog(deName);// 删除好友
			return false;
		}
	}

	public void information() {

		PacketFilter filter = new AndFilter(
				new PacketTypeFilter(Presence.class));

		PacketListener listener = new PacketListener() {

			@Override
			public void processPacket(Packet packet) {
				Presence presence = (Presence) packet;
				// Presence还有很多方法，可查看API
				fromUserJid = presence.getFrom();// 发送方
				String to = presence.getTo();// 接收方
				if (presence.getType().equals(Presence.Type.subscribe)) {// 好友申请

					// 根据配置文件播放提醒声音
					String name = sp.getString("remind", "2");
					if (name.equals("0")) {
						DialUtils.playMusic(FamilyListActivity.this, R.raw.office);
						if (fromUserJid != null) {
							handle.sendEmptyMessage(1);
						}
					}
					// 保存通知消息
					RequestInformation rt = new RequestInformation();
					rt.setuName(Utils.getJidToUsername(fromUserJid));
					rt.setUtime(TimeRender.getDate());
					RequestDBUtils.saveChatInformation(rt, FamilyListActivity.this,
							USERID);
					Log.d("zzzz", "listener好友申请");
				} else if (presence.getType().equals(Presence.Type.subscribed)) {// 同意添加好友
					//弹出提示
					Log.d("zzzz", "listener同意添加好友");
				} else if (presence.getType().equals(Presence.Type.unsubscribe)) {// 拒绝添加好友
					Log.d("zzzz", "listenerunsubscribe");
					// 和

				} else if (presence.getType()
						.equals(Presence.Type.unsubscribed)) {
					Log.d("zzzz", "listenerunsubscribed");

				} else if (presence.getType().equals(Presence.Type.unavailable)) {// 好友下线
																					// 要更新好友列表，可以在这收到包后，发广播到指定页面
					Log.d("zzzz", "listener好友下线");
					// 更新列表

				} else {// 好友上线
					Log.d("zzzz", "listener好友上线");

				}
			}

		};
		XmppTool.con.addPacketListener(listener, filter);

		Presence presence = new Presence(Presence.Type.available);
		XmppTool.con.sendPacket(presence);
		/*roster.addRosterListener(new RosterListener() {
			@Override
			// 监听好友申请消息
			public void entriesAdded(Collection<String> invites) {

				for (Iterator iter = invites.iterator(); iter.hasNext();) {
					String fromUserJids = (String) iter.next();
					fromUserJid = fromUserJids;
					Log.d("zzzz", "收到好友申请消息" + fromUserJids);
				}

				// 保存通知消息
				RequestInformation rt = new RequestInformation();
				rt.setuName(Utils.getJidToUsername(fromUserJid));
				rt.setUtime(TimeRender.getDate());
				RequestDBUtils.saveChatInformation(rt, FamilyListActivity.this,
						USERID);

				// 根据配置文件播放提醒声音
				String name = sp.getString("remind", "2");
				if (name.equals("0")) {
					DialUtils.playMusic(FamilyListActivity.this, R.raw.office);
				}
				Log.d("zzzz", fromUserJid + "fromUserJid是多少");
				if (fromUserJid != null) {
					handle.sendEmptyMessage(1);
				}

			}

			@Override
			// 监听好友同意添加消息
			public void entriesUpdated(Collection<String> invites) {
				Log.d("zzzz", "监听同意添加好友的消息");
				for (Iterator iter = invites.iterator(); iter.hasNext();) {
					String fromUserJids = (String) iter.next();
					Log.d("zzzz", "同意添加的好友是：" + fromUserJids);
					toUserJid = fromUserJids;
				}
				if (toUserJid != null) {
					XmppService.addUserToGroup(toUserJid, pGROUPNAME,
							connection);
				}
				friendInfo = new FriendInfo();
				String nick = ChatUtils.getname(Utils.getJidToUsername(Utils
						.getJidToUsername(fromUserJid)));
				if (nick == null) {
					friendInfo.setNickname(Utils.getJidToUsername(fromUserJid));
				} else {
					friendInfo.setNickname(nick);
				}
				friendInfo.setUsername(Utils.getJidToUsername(fromUserJid));
				friendInfo.setMessageCount(0);
				boolean flag = true;
				for (FriendInfo f : arrayList) {
					if (friendInfo.getJid().equals(f.getJid())) {
						flag = false;
					}
				}
				if (flag) {

					arrayList.add(friendInfo);
				}
				fd.setArrayList(arrayList);
				fd.notifyDataSetChanged();
			}

			@Override
			// 监听好友删除消息
			public void entriesDeleted(Collection<String> delFriends) {
				Log.d("zzzz", "监听到删除好友的消息是：" + delFriends);
				// 这里要刷新好友列表
				if (delFriends.size() > 0) {
				}
			}

			@Override
			// 监听好友状态改变消息
			public void presenceChanged(Presence presence) {
				Log.d("zzzz", "监听到好友状态改变" + presence.getStatus());

			}

		});*/

	}

	public void initView() {

		familyrefresh = (SwipeRefreshLayout) findViewById(R.id.family_refresh);
		familyrefresh.setOnRefreshListener(new RefreshFamily());
		familyrefresh.setColorScheme(R.color.red, R.color.red001, R.color.red,
				R.color.red001);
		set = (ImageView) findViewById(R.id.set_information);
		add_family = (ImageView) findViewById(R.id.add_family);
		seek_family = (ImageView) findViewById(R.id.seek_family);
		notify_family = (ImageView) findViewById(R.id.notify_family);
		add_family.setOnClickListener(new FamilyClick());
		seek_family.setOnClickListener(new FamilyClick());
		notify_family.setOnClickListener(new FamilyClick());
		set.setOnClickListener(new FamilyClick());
		requestQueue = Volley.newRequestQueue(this);

	}

	class FamilyClick implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.add_family:
				intent = new Intent(FamilyListActivity.this,
						AddFamilyActivity.class);
				startActivityForResult(intent, 1);
				break;
			case R.id.seek_family:
				intent = new Intent(FamilyListActivity.this,
						SelectChatsActivity.class);
				startActivity(intent);
				break;
			case R.id.notify_family:
				intent = new Intent(FamilyListActivity.this,
						NotifyActivity.class);
				startActivity(intent);
				break;

			case R.id.set_information:
				startActivity(new Intent(FamilyListActivity.this,
						SetActivity.class));
				break;

			// 点击电话短信聊天
			case R.id.bottomLeft2:
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
						+ Utils.getJidToUsername(arrayList.get(
								(Integer) v.getTag()).getJid())));
				FamilyListActivity.this.startActivity(intent);
				break;
			case R.id.sms_image:
				Uri smsToUri = Uri.parse("smsto:"
						+ Utils.getJidToUsername(arrayList.get(
								(Integer) v.getTag()).getJid()));// 联系人地址
				Intent mIntent = new Intent(
						android.content.Intent.ACTION_SENDTO, smsToUri);
				startActivity(mIntent);
				break;
			case R.id.chat_image:
				Intent intent_image = new Intent(FamilyListActivity.this,
						ChatActivity.class);
				intent_image.putExtra("USERID", USERID);
				intent_image.putExtra("name",
						arrayList.get((Integer) v.getTag()).getJid());
				intent_image.putExtra("nick",
						arrayList.get((Integer) v.getTag()).getNickname());

				intent_image.putExtra("chatUserId",
						arrayList.get((Integer) v.getTag()).getJid());
				startActivity(intent_image);
				break;
			default:
				break;
			}
		}
	}

	/*
	 * 返回
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			FamilyListActivity.this.finish();

		}
		return false;
	}

	public Handler handle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			// 收到好友邀请通知
			case 1:
				familyDialog(fromUserJid);
				break;
			case 19:
				Log.d("zzzz", connection + "connection");
				roster = XmppTool.con.getRoster();
				XmppTool.con.addConnectionListener(new ConnectionXmpp());

				familyList();// 加载好友列表
				// offlinemsg();// 离线消息
				monitorMessage();
				// isInvite();
				information();
				break;
			default:
				break;
			}
		}
	};
	private SwipeRefreshLayout familyrefresh;
	private ListView lv;
	private ChatManager cm;

	// 下面专门处理离线消息
	public void offlinemsg() {
		String log = XmppTool.getConnection().getUser().split("@")[0];
		OfflineMessageManager offlineMessageManager = new OfflineMessageManager(
				XmppTool.con);
		try {
			Log.d("zzzz", (offlineMessageManager.getMessageCount()) + "");
		} catch (XMPPException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			Iterator<org.jivesoftware.smack.packet.Message> it = offlineMessageManager
					.getMessages();

			while (it.hasNext()) {
				org.jivesoftware.smack.packet.Message message = it.next();
				System.out
						.println("收到离线消息, Received from 【" + message.getFrom()
								+ "】 message: " + message.getBody());
				String fromUser = message.getFrom().split("@")[0];
				String msg = message.getBody();
			}
			offlineMessageManager.deleteMessages();
		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 自定义dialog删除好友
	protected void dialog(final String name) {
		final CustomDialog dialog = new CustomDialog(getParent(),
				R.layout.dialog_add_family);
		View view = dialog.getCustomView();
		TextView family_dialog_detial = (TextView) view
				.findViewById(R.id.family_dialog_detial);
		TextView custom_dialog_title = (TextView) view
				.findViewById(R.id.custom_dialog_title);
		custom_dialog_title.setText("删除好友");
		family_dialog_detial.setText("确认删除【" + Utils.getJidToUsername(name)
				+ "】吗？");
		dialog.setLeftOnClick(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				boolean flag = false;// 判断删除是否成功

				flag = XmppService.removeUser(roster, name);
				Log.d("zzzz", flag + "删除好友");

				if (flag == false) {
					Toast.makeText(FamilyListActivity.this, "删除失败",
							Toast.LENGTH_SHORT).show();
				} else {
					arrayList.clear();
					Toast.makeText(FamilyListActivity.this, "成功删除好友",
							Toast.LENGTH_SHORT).show();
					familyList();
				}
				dialog.dismiss();
			}
		});
		dialog.setRightOnClick(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	// 好友申请dialog
	protected void familyDialog(final String name) {
		final CustomDialog dialog = new CustomDialog(getParent(),
				R.layout.dialog_add_family);
		View view = dialog.getCustomView();
		TextView family_dialog_detial = (TextView) view
				.findViewById(R.id.family_dialog_detial);
		TextView custom_dialog_title = (TextView) view
				.findViewById(R.id.custom_dialog_title);
		custom_dialog_title.setText("收到好友申请");
		family_dialog_detial.setText("【" + Utils.getJidToUsername(name) + "】请求加您为好友");
		dialog.setLeftOnClick(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 下面为添加好友的代码
				// 允许添加好友则回复消息，被邀请人应当也发送一个邀请请求。
				Presence subscription = new Presence(Presence.Type.subscribe);
				subscription.setTo(fromUserJid);
				XmppTool.con.sendPacket(subscription);
				if (pGROUPNAME == null) {
					pGROUPNAME = "我的好友";
				}
 
				//XmppService.addUserToGroup(fromUserJid, pGROUPNAME, connection);

				friendInfo = new FriendInfo();
				friendInfo.setUsername(Utils.getJidToUsername(fromUserJid));
				friendInfo.setMessageCount(0);
				boolean flag = true;
				for (FriendInfo f : arrayList) {
					if (friendInfo.getJid().equals(f.getJid())) {
						flag = false;
					}
				}
				if (flag) {
					arrayList.add(friendInfo);
				}
				Log.d("zzzz", arrayList.size() + "加好友之后的好友个数");
				fd.setArrayList(arrayList);
				fd.notifyDataSetChanged();
				dialog.dismiss();
			}
		});
		dialog.setRightOnClick(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				XmppService.removeUser(roster, name);
			}
		});
		dialog.show();
	}

	public void post() {
		Map<String, String> map = new HashMap<String, String>();
		GetInformation userInfo = new GetInformation();
		userInfo.setUsername(sp.getString("username", ""));
		GetInformationBean user = new GetInformationBean();
		user.setHead("getUserInfoServlet");
		user.setContent(userInfo);
		// msg值
		String msg = JsonUtil.objectToString(user, GetInformationBean.class);
		String url = Constant.URL + "?msg=" + msg;
		Log.d("zzzz", url);
		StringRequest request = new StringRequest(url, new ls(), new el());
		requestQueue.add(request);
	}

	// 调用服务器接口发送验证码

	class ls implements Listener<String> {

		@Override
		public void onResponse(String arg0) {
			Log.d("zzzz", arg0);
			BackUserinformation br = (BackUserinformation) JsonUtil
					.StringToObject(arg0, BackUserinformation.class);
			if (br.getStatus().equals("SUCCESS")) {
				Toast.makeText(FamilyListActivity.this, br.getMessage(),
						Toast.LENGTH_SHORT).show();
				ui = br.getData();
				Log.d("zzzz", ui.getBirthdate() + "birthday");
				UserInfo user = new UserInfo();
				user.setUsername(ui.getUsername());
				user.setUserId(ui.getUsername());
				user.setNickname(ui.getNickname());
				user.setSex(ui.getSex());
				user.setEmail(ui.getEmail());
				user.setLoginType(true);
				UserCache.getInstance().addUser(FamilyListActivity.this, user);
			}

			if (br.getStatus().equals("FALURE")) {
				Toast.makeText(FamilyListActivity.this, "获取用户信息失败",
						Toast.LENGTH_SHORT).show();
			}

		}

	}

	class el implements ErrorListener {

		@Override
		public void onErrorResponse(VolleyError arg0) {
			Toast.makeText(FamilyListActivity.this, "请求失败", Toast.LENGTH_SHORT)
					.show();
		}

	}

	class RefreshFamily implements OnRefreshListener {

		@Override
		public void onRefresh() {
			arrayList.clear();
			Collection<RosterEntry> groups = roster.getEntries();
			for (RosterEntry entry : groups) {
				chatUserId = entry.getUser();
				if ("both".equals(entry.getType().name())) {// 只添加双边好友
					friendInfo = new FriendInfo();
					friendInfo.setUsername(Utils.getJidToUsername(entry
							.getUser()));
					String nick = ChatUtils.getname(Utils
							.getJidToUsername(entry.getUser()));
					if (nick == null) {
						friendInfo.setNickname(entry.getName());
					} else {
						friendInfo.setNickname(nick);
					}
					try {
						Bitmap mp = ChatUtils.getUserImage(Utils
								.getJidToUsername(entry.getUser()));

						friendInfo.setPic(mp);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					friendInfo.setMessageCount(0);
					arrayList.add(friendInfo);
					Log.d("zzzz", arrayList.size() + "好友的个数");
					friendInfo = null;
				}
			}

			USERID = sp.getString("username", "1");
			fd.setArrayList(arrayList);
			fd.notifyDataSetChanged();
			familyrefresh.setRefreshing(false);
		}

	}

	// 重连xmpp
	class ConnectionXmpp implements ConnectionListener {
		private Timer tExit;
		private String username;
		private String password;
		private int logintime = 10000;

		@Override
		public void connectionClosed() {
			Log.i("zzzz", "連接關閉");
			// 關閉連接
			XmppTool.closeConnection();
			// 重连服务器
			tExit = new Timer();
			tExit.schedule(new timetask(), logintime);
		}

		@Override
		public void connectionClosedOnError(Exception e) {
			Log.i("zzzz", "連接關閉異常");  
	        // 判斷為帳號已被登錄  
	        boolean error = e.getMessage().equals("stream:error (conflict)");  
	        if (!error) {  
	            // 關閉連接  
				XmppTool.closeConnection();
	            // 重连服务器  
	            tExit = new Timer();  
	            tExit.schedule(new timetask(), logintime);  
	        }  			// TODO Auto-generated method stub

		}

		@Override
		public void reconnectingIn(int arg0) {
			Log.i("zzzz", "reconnectingIn");  

		}

		@Override
		public void reconnectionFailed(Exception arg0) {
			Log.i("zzzz", "reconnectionFailed");  

		}

		@Override
		public void reconnectionSuccessful() {
			Log.i("zzzz", "reconnectionSuccessful");  

		}

	}
	
	  class timetask extends TimerTask {  
	        @Override  
	        public void run() {  
	        	while(true){
	        		try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	        	Log.d("zzzz", "正在重新登录");
	           //重新登录
	        	String account = sp.getString("username", "1");
	        	String password = sp.getString("password", "1");
	        	try {
					XmppTool.getConnection().login(account,
							password);
					//设置登录状态
					Presence presence = new Presence(
							Presence.Type.available);
					XmppTool.getConnection().sendPacket(presence);
					//设置消息监听
					connection = XmppTool.con;
					Log.d("zzzz", XmppTool.con.toString());
					cm = XmppTool.con.getChatManager();
					cm.addChatListener(new chatListener());
					connection.addConnectionListener(new ConnectionXmpp());
					Log.d("zzzz", "登录成功");
					break;
				} catch (XMPPException e) {
					// TODO Auto-generated catch block
					Log.d("zzzz", "登录失败");
					e.printStackTrace();
				}catch (IllegalStateException e) {
					Log.d("zzzz", "登录失败");
					XmppTool.closeConnection();

				}
	        	}
	        }  
	  }
}
